<template>
  <el-container>
    <el-header>
      <div class="header-content">
        建筑业从业人员继续教育考试系统
      </div>
    </el-header>
    <el-main v-loading="loading">
      <el-row type="flex" class="row-bg" justify="center" :gutter="12">
        <el-col :span="5">
          <el-card shadow="always">
            <div class="time" slot="header">
              考生信息
            </div>
            <div style="min-height: 320px;">
              <el-row class="user-item">
                <el-col :span="24" class="user-title">考生姓名：</el-col>
                <el-col :span="24">{{ userInfor && userInfor.userName }}</el-col>
              </el-row>
              <el-row class="user-item">
                <el-col :span="24" class="user-title">身份证号：</el-col>
                <el-col :span="24">{{ userInfor && userInfor.idCard }}</el-col>
              </el-row>
              <el-row class="user-item">
                <el-col :span="24" class="user-title">考生性别：</el-col>
                <el-col :span="24">{{ userInfor && userInfor.gender }}</el-col>
              </el-row>
              <el-row class="user-item">
                <el-col :span="24" class="user-title">企业名称：</el-col>
                <el-col :span="24">{{ userInfor && userInfor.orgName }}</el-col>
              </el-row>
              <el-row class="user-item">
                <el-col :span="24" class="user-title">考试类别：</el-col>
                <el-col :span="24">{{ userInfor && userInfor.userRole }}</el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="always">
            <div slot="header" class="clearfix qus-title-header">
                <div class="qus-title">{{ examInfor && examInfor.period }}</div>
                <div class="qus-info">
                  <el-row type="flex" justify="center" :gutter="12">
                    <el-col :span="5">
                      <span>考试题数：{{ examInfor && examInfor.qusNum }}道</span>
                    </el-col>
                    <el-col :span="5">
                      <span>考试时间：{{ examInfor && examInfor.singleTime }}分钟</span>
                    </el-col>
                    <el-col :span="5">
                      <span>满分：{{ examInfor && examInfor.totalScore }}分</span>
                    </el-col>
                    <el-col :span="5">
                      <span>及格分：{{ examInfor && examInfor.passScore }}分</span>
                    </el-col>
                  </el-row>
                </div>
            </div>
            <div class="qus-content">
              <div class="qus-type-title">
                <span>
                  {{numArr[getQusType(qusList[currentIndex-1].type).index]}}、{{getQusType(qusList[currentIndex-1].type).qusTypeDesc}}题
                  <span style="color: #a3a49d;font-size: 14px;">（共{{ getQusType(qusList[currentIndex-1].type).qusNum}}题）</span>
                </span>
              </div>
              <div class="qus-subject">
                <a href="#" style="color: #1a8cff;">[
                  {{getQusType(qusList[currentIndex-1].type).qusTypeDesc}}题
                ]</a>
                {{ currentIndex}}、{{ qusList[currentIndex-1].question }}
              </div>
              <div class="qus-option-content">
                <el-radio-group v-model="currentAnswer" @change="changeAnswer">
                  <el-radio v-for="(item,index) in qusList[currentIndex-1].option" :label="item.title" :key="item.id">
                    <span class="qus-option-item">{{ item.id }}</span>
                    <span style="color: #606266;">{{ item.title }}</span>
                  </el-radio>
                </el-radio-group>
              </div>
              <div class="qus-btn-group">
                <el-button type="primary" @click="handlePreNext(-1)" :disabled="currentIndex === 1">上一题</el-button>
                <el-button type="primary" @click="handlePreNext(1)" :disabled="currentIndex === qusList.length">下一题</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card shadow="always">
            <div class="time">
              <i class="el-icon-alarm-clock" style="margin-right: 6px;font-size: 28px;"></i>
              {{  countDown(endTime) }}
            </div>
          </el-card>
          <el-card class="other-gutter custom-radio-button" shadow="always" v-if="reFresh">
            <div class="qus-item" v-for="(qus,index) in examInfor.examQusList">
              <div class="qus-item-title">{{ qus.qusTypeDesc }}题</div>
               <el-radio-group v-model="currentIndex" @change="changeIndex">
                  <template v-for="(item,index) in qusList">
                    <el-radio-button
                      v-if="item.type === qus.qusType"
                      :label="item.currentIndex"
                      :key="item.id"
                      style="margin-top: -2px;"
                      :class="{'is-anwsered':item.answered == 1}"
                    ></el-radio-button>
                  </template>
                </el-radio-group>
            </div>
            <div class="sub-btn">
              <el-button type="primary" style="width: 200px;" @click="handleSubmit">交卷</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
    <el-footer>
      <span>技术支持：贵阳市金阳建设数据服务有限公司</span>
    </el-footer>
  </el-container>
</template>

<script>
  import request from '@/utils/request'
  import axios from 'axios'
  import moment from 'moment'
  export default {
    name: 'ExamHome',
    data() {
      return {
        Urls: {
          examGetByExamIdUrl: '/api/exam/detail/get/',
          // 当前用户信息
          currentUserInfoUrl: '/api/examUser/query',
          // 考试
          answerExamUrl: '/api/answer/exam/',
          // 考试结果
          resultUrl: '/api/exam/record/result/',
          qusUrl: '/api/answer/begin/',
          // 答案
          answerUrl: '/api/answer/answer',
          // 交卷
          submitExamUrl: '/api/answer/submit/'
        },
        examId: localStorage.getItem('examId'),
        examType: localStorage.getItem('examType'),
        name: localStorage.getItem('name'),
        userName: localStorage.getItem('mark'),
        id: localStorage.getItem('id'),
        now: moment(),
        endTime: 60*1000,
        examInfor: {
          qusNum: 0,
          totalScore: 0,
          passScore: 0,
          period: '',
          examQusList: [
            {
            	"old": null,
            	"examId": "1504261230788497410",
            	"qusScore": 1.0,
            	"qusType": "choice",
            	"qusNum": 50,
            	"qusTypeDesc": "单选",
            	"randomType": 1,
            	"status": "NORMAL",
            	"modifyTime": null,
            	"creator": null,
            	"createTime": "2022-03-17 09:00:00",
            	"modifier": null,
            	"statusDesc": "正常",
            	"id": "1504261230788497411"
            }, {
            	"old": null,
            	"examId": "1504261230788497410",
            	"qusScore": 1.0,
            	"qusType": "judge",
            	"qusNum": 50,
            	"qusTypeDesc": "判断",
            	"randomType": 1,
            	"status": "NORMAL",
            	"modifyTime": null,
            	"creator": null,
            	"createTime": "2022-03-17 09:00:00",
            	"modifier": null,
            	"statusDesc": "正常",
            	"id": "1504261230801080322"
            }
          ],
          singleTime: 0
        },
        numArr: ["一","二","三","四","五","六","七","八","九"],
        currentIndex: 1,
        currentAnswer: '',
        userInfor: {},
        answered: false,
        qusList: [
          {
            id: '1',
            type: 'choice',
            options: [
              {
                title: '突发事件预警信息包括可能发生的突发事件的类别、()、起始时间、可能影响范围、警示事项、应采取的措施和发布机关等',
                id: 'A'
              }
            ]
          }
        ],
        reFresh: true,
        loading: false,
        interval: null,
        submit: 0
      }
    },
    created() {
      // 获取考试剩余时间
      this.startExam()
      // 获取试卷信息
      this.getExamInfo()
      // 获取考生信息
      this.getUserInfo()
    },
    mounted() {
    	  //定时更新当前时间
    	 this.interval = window.setInterval(()=>{
         this.endTime = this.endTime - 1000
    	 },1000)
    },
    computed: {
    	//计算属性，返回剩余时间
    	countDown(){
    	  return function() {
          if (this.endTime > 0) {
            //得到一个对象，里面有对应的时分秒等时间对象值
            let time = moment.duration(this.endTime, 'milliseconds')
            let hours = time.hours()
            let minutes = time.minutes()
            let seconds = time.seconds()
            return moment({h:hours, m:minutes, s:seconds}).format('HH:mm:ss')
          } else {
            if (!this.answered) {
              console.log(this.answered,1)
              this.content = '您的答题时间已到，系统已自动提交'
              // 交卷
              this.handleJump()
            }
            if (this.interval) {
              // 清除计时器
              window.clearInterval(this.interval)
            }
            return "00:00:00"
          }
    	  }
    	}
    },
    methods: {
      changeIndex(val) {
        this.reFresh = false
        this.$nextTick(() => {
          this.currentAnswer = this.qusList[this.currentIndex-1].answer
          this.reFresh = true
        })
      },
      /**
       * 回答
       * @param {Object} val
       */
      changeAnswer(val) {
        this.qusList[this.currentIndex-1].answer = val
        this.qusList[this.currentIndex-1].checked = true
        // 提交答案
        this.handleAnswer()
      },
      /**
       * 提交答案
       */
      handleAnswer() {
        const _this = this
        let answers = []
        answers.push(_this.qusList[_this.currentIndex-1].answer)
        let form = {
          ansRecordId: _this.qusList[_this.currentIndex-1].id,
          answer:  answers,
          examId: _this.qusList[_this.currentIndex-1].examId,
          qusId: _this.qusList[_this.currentIndex-1].qusId,
          userId: _this.qusList[_this.currentIndex-1].userId,
        }
        request({
          url: _this.Urls.answerUrl,
          method: 'post',
          data: form
        }).then(res => {
          if (res.code == 0) {
            _this.qusList[_this.currentIndex-1].answered = res.data.answered
          } else{
            _this.$notify.error({
              message: res.msg
            })
          }
        })
      },
      /**
       * 交卷
       */
      handleSubmit() {
        const _this = this
        let content = ''
        let cancelText = ''
        let emptyQuestions = []
        let checkedIndex = 0
        _this.qusList.forEach((item, index) => {
          if (item.answered != 1) {
            if (checkedIndex == 0) {
              checkedIndex = index
            }
            emptyQuestions.push(item)
          }
        })
        if (emptyQuestions.length == 0) { // 题目全答完
          content = '提交后不可再进行修改，确定要提交吗？'
          cancelText = '我再想想'
        } else {
          content = `当前有${emptyQuestions.length}题未做，确定提交？`
          cancelText = '去答题'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
            cancelButtonText: cancelText,
            type: 'warning'
          }).then(() => {
            _this.content = '试卷已提交，请查看考试结果'
            // 交卷
            this.handlePaper()
          }).catch(() => {
            if (checkedIndex != 0) {
              _this.currentIndex = checkedIndex + 1
            }
          })
      },
      /**
       * 计时结束
       */
      handleJump() {
        const _this = this
        _this.answered = true
        _this.$alert(_this.content, '提示', {
          confirmButtonText: '查看考试结果',
            callback: action => {
              _this.$router.push({
                path: '/exam-result'
              })
            }
        })
      },
      /**
       * 交卷
       */
      handlePaper() {
        const _this = this
        _this.loading = true
        // _this.endTime = 0
        // _this.answered = true
        request({
          url: _this.Urls.submitExamUrl + _this.examId,
          method: 'get',
          data: {}
        }).then(res => {
          _this.loading = false
          if (res.code == 0) {
            _this.answered = true
            _this.endTime = 0
            _this.dialogVisible = false
            this.$alert(_this.content, '提示', {
              confirmButtonText: '查看考试结果',
                callback: action => {
                  _this.$router.push({
                    path: '/exam-result'
                  })
                }
            })
          } else{
            _this.$notify.error({
              message: res.msg
            })
          }
        }).catch(err => {
          console.log(err)
          _this.loading = false
        })
      },
      /**
       * 考试信息
       */
      getExamInfo() {
        const _this = this
        request({
          url: _this.Urls.examGetByExamIdUrl + _this.examId,
          method: 'get',
          data: {}
        }).then(res => {
          if (res.code == 0) {
            _this.examInfor = {
              qusNum: res.data.qusNum,
              totalScore: res.data.totalScore,
              passScore: res.data.passScore,
              period: res.data.period,
              examQusList: res.data.examQusList,
              singleTime: res.data.singleTime
            }
          } else{
            _this.$notify.error({
              message: res.msg
            })
          }
        })
      },
      /**
       * 用户信息
       */
      getUserInfo() {
        const _this = this
        request({
          url: _this.Urls.currentUserInfoUrl,
          method: 'post',
          data: {
            userId: _this.id,
            examId: _this.examId
          }
        }).then(res => {
          if (res.code == 0) {
            _this.userInfor = {
              ...res.data.records[0]
            }
          } else{
            _this.$notify.error({
              message: res.msg
            })
          }
        })
      },
      /**
       * 开始考试
       */
      startExam() {
        const _this = this
        request({
          url: _this.Urls.answerExamUrl + _this.examId,
          method: 'get',
          data: {}
        }).then(res => {
          if (res.code == 0) {
            _this.endTime = res.data.remaining
            _this.getSubjects()
          } else{
            if (res.code == 1205) {
              _this.$router.push({
                path: '/exam-result'
              })
            } else{
              _this.$notify.error({
                message: res.msg
              })
            }
          }
        })
      },
      /**
       * 题目
       * @param {Object} type
       * @param {Object} examId
       */
      getQuestions(type, examId) {
        if (examId) {
          return request.get(this.Urls.qusUrl + examId + '/' + type)
        }
      },
      randomSort(a, b) {
        return Math.random() >.5?-1:1
      },
      getSubjects() {
        const _this = this
        let requestMethods = []
        for (var i = 0; i < _this.examInfor.examQusList.length; i++) {
          requestMethods.push(_this.getQuestions(_this.examInfor.examQusList[i].qusType, _this.examId))
        }
        axios.all(requestMethods)
          .then((function(result){
            let querstions = []
            if(result && result.length > 0) {
              for (var i = 0; i < result.length; i++) {
                if (result[i].code === 0) {
                  querstions = querstions.concat(result[i].data)
                } else {
                  _this.$notify.error({
                    message: result[i].msg
                  })
                  break
                }
              }
            }
            let options = []
            let formatOptions = []
            let modifTime = null
            let currentIndex = 1
            let answer = ''
            querstions.forEach((item, index) => {
              if (!modifTime && item.modifyTime) {
                currentIndex = index + 1
                answer = item.answer
                modifTime = item.modifyTime
              } else if (modifTime && item.modifyTime) {
                if (new Date(item.modifyTime) - new Date(modifTime) >= 0) {
                  modifTime = item.modifyTime
                  currentIndex = index + 1
                  answer = item.answer
                }
              }
              formatOptions = []
              options = []
              item['checked'] = false
              options = item.options?item.options.split(';') : []
              options.sort(_this.randomSort)
              options.forEach((option, order) => {
                formatOptions.push({
                  id: String.fromCharCode('A'.charCodeAt(0) + order),
                  title: option
                })
              })
              item['currentIndex'] = index + 1
              item['option'] = formatOptions
            })
            _this.currentIndex = currentIndex
            _this.currentAnswer = answer
            _this.qusList = [...querstions]
          }))
      },
      /**
       * 上一题、下一题
       * @param {Number} index -1、1
       */
      handlePreNext(index) {
        this.currentIndex = this.currentIndex + index
        this.currentAnswer = this.qusList[this.currentIndex-1].answer
      },
      getQusType(type) {
        if(type) {
          let qusTypes = this.examInfor.examQusList.filter((item, index) => {
            if (item.qusType === type) {
              item['index'] = index
              return item
            }
          })
          return qusTypes[0]
        }
      }
    }
  }
</script>

<style scoped="scoped">
  .el-container {
    height: 100vh;
    flex-direction: column;
  }

  .el-header, .el-footer {
      background-color: #B3C0D1;
      line-height: 60px;
    }
    .el-header {
      background-color: #fff;
    }
    .header-content {
      width: 90%;
      margin: 0 auto;
      color: #1a8cff;
      font-size: 24px;
    }
    .el-footer {
      font-weight: 400;
      text-align: center;
      background-color: #000;
      color: #fff;
    }
    .el-main {
      flex: 1;
      overflow: auto;
      background-color: #E9EEF3;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
      clear: both
    }
    .qus-title-header {
      text-align: center;
    }
    .qus-title {
      font-weight: bold;
      font-size: 16px;
    }
    .qus-content {
      min-height: 400px;
    }
    .qus-info {
      margin-top: 12px;
      font-size: 14px;
    }
    .other-gutter {
      margin-top: 12px;
    }
    .time {
      text-align: center;
      font-size: 20px;
    }
    .qus-item {
      margin-bottom: 24px;
    }
    .qus-item-title {
      font-weight: bold;
      margin-bottom: 12px;
    }
    .qus-subject {
      margin-top: 16px;
      line-height: 24px;
    }
    .qus-option-content {
      margin-top: 24px;
    }
    .qus-option-content .el-radio {
      margin-bottom: 12px;
      display: block;
    }
    .qus-option-content .is-checked span:first-child {
      background-color: #409eff;
      color: #fff;
    }
    .qus-option-item {
      display: inline-block;
      padding: 4px;
      height: 24px;
      width: 24px;
      border-radius: 24px;
      border:1px solid #DCDFE6;
      vertical-align: middle;
      text-align: center;
      margin-right: 12px;
    }
    .qus-btn-group {
      margin-top: 48px;
      text-align: center;
    }
    .qus-btn-group button {
      width: 100px;
    }
    .qus-btn-group button:first-child {
      margin-right: 24px;
    }
    .sub-btn {
      width: 100%;
      text-align: center;
      padding-top: 32px;
    }
    .user-item {
      text-align: right;
      margin-bottom: 24px;
    }
    .user-title {
      text-align: left;
      color: #a3a49d;
    }

</style>
